package com.zxj;

import java.io.IOException;


import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


public class DataCount {


    public static class DCMapper extends Mapper<LongWritable, Text, Text, DataBean>{


        @Override
        protected void map(LongWritable key, Text value, Context context)
                throws IOException, InterruptedException {
            //accept
            String line = value.toString();
            //split
            String[] fields = line.split("\t");
            String tel = fields[1];
            long up = Long.parseLong(fields[7]);
            long down = Long.parseLong(fields[8]);
            DataBean bean = new DataBean(up, down);
            //send
            context.write(new Text(tel), bean);
        }

    }

    public static class DCReducer extends Reducer<Text, DataBean, Text, DataBean>{


        @Override
        protected void reduce(Text key, Iterable<DataBean> values, Context context)
                throws IOException, InterruptedException {
            long upSum = 0;
            long downSum = 0;
            for(DataBean bean : values){
                upSum += bean.getUpPayLoad();
                downSum += bean.getDownPayLoad();
            }
            DataBean bean = new DataBean(upSum, downSum);
            context.write(key, bean);
        }


    }


    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        //1、获取job信息
        Job job = Job.getInstance(conf);
        //2、获取jar的存储路径
        job.setJarByClass(DataCount.class);
        //3、关联map和reduce的class类
        job.setMapperClass(DCMapper.class);
        job.setReducerClass(DCReducer.class);
        //4、设置map阶段输出的key和value类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(DataBean.class);
        //5、设置最后输出数据的key和value类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(DataBean.class);
        //6、设置输入数据的路径和输出数据的路径
        FileInputFormat.setInputPaths(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));
        //7、提交
        job.waitForCompletion(true);

    }
}